package com.zhongjian.technologycal.mall.activity.main.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.transformer.DepthPageTransformer;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.LoginActivity;
import com.zhongjian.technologycal.mall.activity.shoppingcart.activity.ShoppingCartActivity;
import com.zhongjian.technologycal.mall.adapter.GalleryAdapter;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.base.BaseContacts;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.ProductDetailsBean;
import com.zhongjian.technologycal.mall.interfacemall.ScrollViewListener;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.PicassoImageLoader;
import com.zhongjian.technologycal.mall.utils.PicassoRoundTransform;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.LogUtils;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.view.ObservableScrollView;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.onekeyshare.OnekeyShare;
import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/11/17.
 * 商品详情实现页面
 * <p>
 * beLongToVIP":false 有加入购物车的按钮
 * beLongToVIP":true 立即购买，没有加入购物车按钮
 */

public class ProductsDetailsActivity extends BaseActivity {
    @BindView(R.id.rl_product_colege)
    RelativeLayout rl_product_colege;
    @BindView(R.id.details_banner)
    Banner details_banner;
    @BindView(R.id.product_wb_details)
    WebView product_wb_details;
    private String productId;
    @BindView(R.id.product_tv_shopping)
    TextView product_tv_shopping;
    @BindView(R.id.product_tv_details)
    TextView product_tv_details;
    @BindView(R.id.product_tv_comment)
    TextView product_tv_comment;

    @BindView(R.id.scrollView_product_details)
    ObservableScrollView scrollView_product_details;
    @BindView(R.id.products_ll_details)
    LinearLayout products_ll_details;
    @BindView(R.id.products_rl_comment)
    RelativeLayout products_rl_comment;
    @BindView(R.id.iv_share)
    ImageView iv_share;
    @BindView(R.id.id_recyclerview_horizontal)
    RecyclerView id_recyclerview_horizontal;

    @BindView(R.id.details_tv_product_name)
    TextView details_tv_product_name;
    @BindView(R.id.details_tv_product_price)
    TextView details_tv_product_price;
    @BindView(R.id.details_tv_product_credits)
    TextView details_tv_product_credits;
    @BindView(R.id.details_tv_product_count)
    TextView details_tv_product_count;
    @BindView(R.id.details_tv_product_area)
    TextView details_tv_product_area;
    @BindView(R.id.tv_order_cart_commit)
    TextView tv_order_cart_commit;//加入购物车
    @BindView(R.id.tv_order_sale_commit)
    TextView tv_order_sale_commit;//立即购买
    private TextView tv_good_detail_dialog_price;
    private TextView dialog_tv_credis;
    private Dialog dialog;
    private int mPage;
    private TagFlowLayout flowLayout_hot;
    private TagFlowLayout flowLayout_shopping;
    private List<String> arrayList = new ArrayList<>();
    private TagAdapter<String> mAdapter;
    private int top0, top1, top2;
    private String urlPhoto;
    private String pName;
    private int pPrice;
    private List<String> mtagList;
    private List<String> mIdList;
    private List<String> mPriceList;
    private List<String> elecNumList;
    private List<String> spaceNameList;
    private ProductDetailsBean productDetailsBean;
    private int count = 1;
    private Double price;
    private String spid = null;
    //===================
    private String producName;
    private String producImgUrl;
    private String producertel;
    private String elecNum = null;
    private String sprice = null;
    private String spaceName = null;
    private int knum;
    private boolean isBeLongToVIP;
    private Dialog hintDialog = null;
    private MaterialDialog materialDialog = null;
    private String shareUrl;
    private List<String> listItems;
    private GalleryAdapter galleryAdapter;

    //返回布局视图
    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_product_details;
    }

    @Override
    protected void beforeInit() {
        super.beforeInit();
    }


    //初始化界面
    @Override
    protected void initView(Bundle savedInstanceState) {
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
        productId = getIntent().getStringExtra("productId");
        initViewRequest();
        initViewWebView();
        scrollView_product_details.smoothScrollTo(0, 0);

//        listItems = new ArrayList<>(Arrays.asList("棒棒的商品，很nice！下次还买一个",
//                "棒棒的商品，很nice！买了好几个了", "棒棒的商品，很nice！，下次还买一个", "棒棒的商品，很nice！，太棒了", "棒棒的商品，很nice！灰常不错",
//                "棒棒的商品，很nice！good", "棒棒的商品，很nice！good", "棒棒的商品，很nice！小伙伴", "棒棒的商品，很nice！beautiful"));
////
//        galleryAdapter = new GalleryAdapter(ProductsDetailsActivity.this,listItems);
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext());
//        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        id_recyclerview_horizontal.setLayoutManager(linearLayoutManager);
//        id_recyclerview_horizontal.addItemDecoration(new SpaceItemDecoration(5));
//        id_recyclerview_horizontal.setAdapter(galleryAdapter);
    }

    @Override
    public void initPresenter() {

    }

    //返回上一个页面
    @OnClick(R.id.iv_back)
    public void appOnClick() {
        finish();
    }

    //
    //分享详情页面
    @OnClick(R.id.iv_share)
    public void appOnClickShare() {
        shareUrl = BaseContacts.URL_PRODUCT_DETAILS + productId;
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setDialogMode(true);
        oks.setVenueDescription("分享");
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle(producName);
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl(shareUrl);
        // text是分享文本，所有平台都需要这个字段
//        oks.setText(iniviteCodeUrl);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        oks.setImageUrl(producImgUrl);
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(shareUrl);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(shareUrl);
        // 启动分享GUI
        oks.show(this);
    }

    private void initViewRequest() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        } else {
            HttpRetrofitClient.getInstance(getBaseContext())
                    .getUrlRequestProductDetails(
                            Integer.valueOf(productId),
                            new Subscriber<ResponseBody>() {
                                @Override
                                public void onStart() {
                                    super.onStart();
                                    LoadingDialog.showDialogForLoading(ProductsDetailsActivity.this);
                                }

                                @Override
                                public void onCompleted() {
                                    LoadingDialog.cancelDialogForLoading();

                                }

                                @Override
                                public void onError(Throwable e) {
                                    LoadingDialog.cancelDialogForLoading();

                                }

                                @Override
                                public void onNext(ResponseBody responseBody) {
                                    LoadingDialog.cancelDialogForLoading();
                                    try {
                                        Gson gson = new Gson();
                                        productDetailsBean =
                                                gson.fromJson(responseBody.string(), ProductDetailsBean.class);
                                        if (productDetailsBean.getError_code() == 0) {
                                            iv_share.setVisibility(View.VISIBLE);

                                            for (int i = 0; i < productDetailsBean.getData().getProduct().getProductphotos().size(); i++) {
                                                arrayList.add(BaseContacts.BASE_URL + productDetailsBean.getData().getProduct().getProductphotos().get(i).getPhoto());
                                            }
                                            details_banner.setImages(arrayList)
                                                    .setImageLoader(new PicassoImageLoader())
                                                    .setOnBannerListener(new OnBannerListener() {
                                                        @Override
                                                        public void OnBannerClick(int position) {

                                                        }
                                                    })
                                                    .start();
                                            producImgUrl = arrayList.get(0).toString();
                                            producName = productDetailsBean.getData().getProduct().getProductname();
                                            isBeLongToVIP = productDetailsBean.getData().isBeLongToVIP();
                                            details_banner.setBannerAnimation(DepthPageTransformer.class);
                                            details_tv_product_name.setText(productDetailsBean.getData().getProduct().getProductname());
                                            details_tv_product_price.setText("" + productDetailsBean.getData().getProduct().getPrice());
                                            knum = productDetailsBean.getData().getProduct().getStocknum();
                                            details_tv_product_count.setText("库存" + productDetailsBean.getData().getProduct().getStocknum() + "件");

                                            details_tv_product_credits.setText("" + productDetailsBean.getData().getProduct().getElecnum() / 2);
                                            details_tv_product_area.setText(productDetailsBean.getData().getProduct().getPlaceofdelivery());
                                            if (!TextUtils.isEmpty(productDetailsBean.getData().getProduct().getProductphotos().get(0).getPhoto())) {
                                                urlPhoto = BaseContacts.BASE_URL + productDetailsBean.getData().getProduct().getProductphotos().get(0).getPhoto();
                                            } else {

                                            }
                                            if (isBeLongToVIP == true) {
                                                tv_order_cart_commit.setVisibility(View.VISIBLE);
                                                tv_order_cart_commit.setClickable(false);
                                                tv_order_cart_commit.setBackgroundResource(R.color.border_color);
                                            } else {
                                                tv_order_cart_commit.setVisibility(View.VISIBLE);
                                                tv_order_cart_commit.setClickable(true);
                                            }
                                            pName = productDetailsBean.getData().getProduct().getProductname();
                                            mtagList = new ArrayList<>();
                                            mIdList = new ArrayList<>();// BigDecimal
                                            mPriceList = new ArrayList<>();
                                            elecNumList = new ArrayList<>();
                                            spaceNameList = new ArrayList<>();
                                            for (int d = 0; d < productDetailsBean.getData().getProduct().getProductspecs().size(); d++) {
                                                mtagList.add(productDetailsBean.getData().getProduct().getProductspecs().get(d).getSpecname());
                                                mIdList.add(String.valueOf(productDetailsBean.getData().getProduct().getProductspecs().get(d).getId()));
                                                mPriceList.add(String.valueOf(productDetailsBean.getData().getProduct().getProductspecs().get(d).getPrice()));
                                                elecNumList.add(String.valueOf(productDetailsBean.getData().getProduct().getProductspecs().get(d).getElecNum()));
                                                spaceNameList.add(productDetailsBean.getData().getProduct().getProductspecs().get(d).getSpecname());
                                            }
                                            price = productDetailsBean.getData().getProduct().getProductspecs().get(0).getPrice();

                                        }else{
                                            ToastUitl.showShort(productDetailsBean.getError_message());
                                        }

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }


                                }
                            });

        }

    }

    /**
     * 弹出购买对话框
     */
    private void showBuyDialog() {
        dialog = new Dialog(ProductsDetailsActivity.this, R.style.Theme_Light_Dialog);
        Window window = dialog.getWindow();
        View viewDialog = LayoutInflater.from(ProductsDetailsActivity.this).inflate(R.layout.dialog_details_buy, null);

        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        window.setWindowAnimations(R.style.dialog_style);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        dialog.setContentView(viewDialog);
        ImageView iv_good_detail_dialog = dialog.findViewById(R.id.iv_good_detail_dialog);
        tv_good_detail_dialog_price = dialog.findViewById(R.id.tv_good_detail_dialog_price);
        dialog_tv_credis = dialog.findViewById(R.id.dialog_tv_credis);
        TextView tv_good_detail_dialog_stock = dialog.findViewById(R.id.tv_good_detail_dialog_stock);
        Button bt_detail_dialog_ok = dialog.findViewById(R.id.bt_detail_dialog_ok);
        Button bt_detail_dialog_commit = dialog.findViewById(R.id.bt_detail_dialog_commit);
        final LinearLayout iv_dialog_count_jia = dialog.findViewById(R.id.iv_dialog_count_jia);
        final LinearLayout iv_dialog_count_jian = dialog.findViewById(R.id.iv_dialog_count_jian);
        final TextView tv_dialog_count = dialog.findViewById(R.id.tv_dialog_count);
        flowLayout_hot = dialog.findViewById(R.id.flowLayout_buy);
        flowLayout_shopping = dialog.findViewById(R.id.flowLayout_shopping);
//        final RequestOptions options = new RequestOptions();
//        options.centerCrop()
//                .optionalTransform(new GlideRoundTransform())
//                .placeholder(R.mipmap.bg_white2x)
//                .error(R.mipmap.bg_white2x);
//        Glide.with(ProductsDetailsActivity.this)
//                .load(urlPhoto)
//                .apply(options)
//                .thumbnail(0.1f)
//                .into(iv_good_detail_dialog);

        Picasso.get().load(urlPhoto)
                .transform(new PicassoRoundTransform())
                .into(iv_good_detail_dialog);

        tv_good_detail_dialog_price.setText("" + price);
        dialog_tv_credis.setText(details_tv_product_credits.getText().toString());
        tv_good_detail_dialog_stock.setText(details_tv_product_count.getText().toString());
        if (isBeLongToVIP == true) {
            bt_detail_dialog_ok.setVisibility(View.GONE);
        } else if (isBeLongToVIP == false) {
            bt_detail_dialog_ok.setVisibility(View.VISIBLE);
        }
        /**
         * 加入购物车
         */
        bt_detail_dialog_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (spid == null || spid.equals("")) {
                    ToastUitl.showShort("请先选择商品规格～");
                    return;
                } else if (count > knum) {
                    ToastUitl.showShort("购买数量不能大于库存数量～");
                    return;
                }
                initRequestUpdateShoppingCartInfo();
                dialog.dismiss();
            }
        });

        /**
         * 立即购买
         */
        bt_detail_dialog_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (spid == null || spid.equals("")) {
                    ToastUitl.showShort("请先选择商品规格～");
                    return;
                } else if (count > knum) {
                    ToastUitl.showShort("购买数量不能大于库存数量～");
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(getBaseContext(), PaymentOrderActivity.class);
                intent.putExtra("pnum", String.valueOf(count));
                intent.putExtra("pname", String.valueOf(pName));
                intent.putExtra("spid", String.valueOf(spid));
                intent.putExtra("sprice", String.valueOf(sprice));
                intent.putExtra("productId", productId);
                intent.putExtra("elecNum", elecNum);
                intent.putExtra("isBeLongToVIP", isBeLongToVIP);
                intent.putExtra("spaceName", spaceName);
                startActivity(intent);
                dialog.dismiss();
            }
        });

        iv_dialog_count_jia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                count++;
                if (count > knum) {
                    ToastUitl.showShort("不能大于库存数量～");
                    tv_dialog_count.setText("" + count);
                } else {
                    tv_dialog_count.setText("" + count);
                }


            }
        });
        iv_dialog_count_jian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (count == 1) {
                    ToastUitl.showShort("不能小于1件商品～");
                    tv_dialog_count.setText("" + count);
                } else {
                    count--;
                    tv_dialog_count.setText("" + count);
                }

            }
        });

        if (dialog.isShowing()) {

        } else {
            spid = null;
            count = 1;
        }

        dialog.show();
        setDataFlowLayout0();
    }


    /**
     * 设置套餐数据
     */
    private void setDataFlowLayout0() {
        final LayoutInflater mInflater = LayoutInflater.from(ProductsDetailsActivity.this);
        flowLayout_hot.setAdapter(mAdapter = new TagAdapter<String>(mtagList) {
            @Override
            public View getView(FlowLayout parent, int position, String str) {
                TextView tags = (TextView) mInflater.inflate(R.layout.tags_flowlayout_shopping,
                        flowLayout_hot, false);
                tags.setTextSize(10);
                tags.setText(str);
                return tags;
            }
        });
//        flowLayout_hot.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
//            @Override
//            public void onSelected(Set<Integer> selectPosSet) {
//                ToastUitl.showShort(selectPosSet.toString());
//                if (selectPosSet.size() > 0) {
//                    spid =  mIdList.get(0).toString();
//                } else {
//                    ToastUitl.showShort("请先选择商品规格～");
//                }
//
//            }
//        });
        flowLayout_hot.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
//                ToastUitl.showShort(""+ mIdList.get(position).toString());
                spid = mIdList.get(position).toString();
                sprice = mPriceList.get(position).toString();
                elecNum = elecNumList.get(position).toString();
                spaceName = spaceNameList.get(position).toString();
                tv_good_detail_dialog_price.setText("" + sprice);
                dialog_tv_credis.setText("" + Double.valueOf(elecNum) / 2);
                return false;
            }
        });

    }

    private void initViewWebView() {
        product_wb_details.loadUrl(BaseContacts.URL_PRODUCTDETAILS_PRODUCTID + productId);
        WebSettings settings = product_wb_details.getSettings();
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(true);

        product_wb_details.setWebChromeClient(new MyWebChrome());
        product_wb_details.setWebViewClient(new MyWebClient());
    }


    /**
     * 加入购物车请求
     */
    private void initRequestUpdateShoppingCartInfo() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .postUrlRequestCartInfo(Integer.valueOf(productId), Integer.valueOf(spid),
                        UserUtils.getUserToken(), count, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                LoadingDialog.showDialogForLoading(ProductsDetailsActivity.this);
                            }

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                LoadingDialog.cancelDialogForLoading();
                                try {
                                    Gson gson = new Gson();
                                    BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                                    if (baseBean.getError_code() == 0) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    } else if (baseBean.getError_code() == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }
                        });

    }

    private class MyWebChrome extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    }


    private class MyWebClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtils.logd("截取URL", url);
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        top0 = details_banner.getTop();
        top1 = products_ll_details.getTop();
        top2 = products_rl_comment.getTop();

        scrollView_product_details.setScrollViewListener(new ScrollViewListener() {
            @Override
            public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
                if (y < 900) {
                    product_tv_shopping.setTextColor(getResources().getColor(R.color.blue));
                    product_tv_details.setTextColor(getResources().getColor(R.color.colorTextGray));
                    product_tv_comment.setTextColor(getResources().getColor(R.color.colorTextGray));
                } else if (y > 1450 && y < 1590) {
                    product_tv_shopping.setTextColor(getResources().getColor(R.color.colorTextGray));
                    product_tv_details.setTextColor(getResources().getColor(R.color.colorTextGray));
                    product_tv_comment.setTextColor(getResources().getColor(R.color.blue));

                } else if (y > 1590) {
                    product_tv_shopping.setTextColor(getResources().getColor(R.color.colorTextGray));
                    product_tv_comment.setTextColor(getResources().getColor(R.color.colorTextGray));
                    product_tv_details.setTextColor(getResources().getColor(R.color.blue));
                }
            }
        });

    }


    @Override
    public void onBackPressed() {
        product_wb_details.goBack();
        super.onBackPressed();

    }

    /**
     * 选择分类
     */
    @OnClick(R.id.rl_product_colege)
    public void onClikProductColege() {
        Intent intent = new Intent();
        if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
            intent.setClass(getBaseContext(), LoginActivity.class);
            startActivity(intent);
        } else {
            showBuyDialog();
        }
    }

    /**
     * 商品
     */
    @OnClick(R.id.product_tv_shopping)
    public void onClickProductShopping() {
        scrollView_product_details.smoothScrollTo(0, top0);
        product_tv_shopping.setTextColor(getResources().getColor(R.color.blue));
        product_tv_details.setTextColor(getResources().getColor(R.color.colorTextGray));
        product_tv_comment.setTextColor(getResources().getColor(R.color.colorTextGray));

    }

    /**
     * 详情
     */
    @OnClick(R.id.product_tv_details)
    public void onClickProductDetails() {
        scrollView_product_details.smoothScrollTo(0, top1);
        product_tv_shopping.setTextColor(getResources().getColor(R.color.colorTextGray));
        product_tv_details.setTextColor(getResources().getColor(R.color.blue));
        product_tv_comment.setTextColor(getResources().getColor(R.color.colorTextGray));
    }

    /**
     * 评论
     */
    @OnClick(R.id.product_tv_comment)
    public void onClickProductComment() {
        scrollView_product_details.smoothScrollTo(0, top2);
        product_tv_shopping.setTextColor(getResources().getColor(R.color.colorTextGray));
        product_tv_details.setTextColor(getResources().getColor(R.color.colorTextGray));
        product_tv_comment.setTextColor(getResources().getColor(R.color.blue));
    }

    /**
     * 加入购物车
     */
    @OnClick(R.id.tv_order_cart_commit)
    public void onClickCartCommit() {
        Intent intent = new Intent();
        if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
            intent.setClass(getBaseContext(), LoginActivity.class);
            startActivity(intent);
        } else {
            showBuyDialog();
        }
    }

    @OnClick({R.id.service_ll_people, R.id.service_ll_cart, R.id.service_ll_collection})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.service_ll_people:
                if (ContextCompat.checkSelfPermission(ProductsDetailsActivity.this,
                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // 没有获得授权，申请授权
                    if (ActivityCompat.shouldShowRequestPermissionRationale(ProductsDetailsActivity.this,
                            Manifest.permission.CALL_PHONE)) {
                        // 返回值：
//                          如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//                          如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//                          如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                        // 弹窗需要解释为何需要该权限，再次请求授权
                        ToastUitl.showShort("请授权");

                        // 帮跳转到该应用的设置界面，让用户手动授权
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivity(intent);
                    } else {
                        // 不需要解释为何需要该权限，直接请求授权
                        ActivityCompat.requestPermissions(ProductsDetailsActivity.this,
                                new String[]{Manifest.permission.CALL_PHONE},
                                1003);
                    }
                } else {
                    // 已经获得授权，可以打电话
                    callPhone();
                }
                break;
            //购物车
            case R.id.service_ll_cart:
                Intent intent = new Intent();
                if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
                    intent.setClass(getBaseContext(), LoginActivity.class);
                    startActivity(intent);
                } else {
                    intent.setClass(getBaseContext(), ShoppingCartActivity.class);
                    startActivity(intent);
                }
                break;
            /**
             * 收藏
             */
            case R.id.service_ll_collection:
                ToastUitl.showShort("敬请期待...");
                break;
        }
    }


    /**
     * 立即购买
     */
    @OnClick(R.id.tv_order_sale_commit)
    public void onClickSaleCommit() {
        Intent intent = new Intent();
        if (UserUtils.getUserToken() == null || UserUtils.getUserToken().equals("")) {
            intent.setClass(getBaseContext(), LoginActivity.class);
            startActivity(intent);
        } else {
            showBuyDialog();
        }

    }

    /**
     * 拨打客服电话
     */
    private void callPhone() {
        materialDialog = new MaterialDialog(ProductsDetailsActivity.this)
                .setTitle("客服电话")
                .setMessage("0571-57183790")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0571-57183790"));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        materialDialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        materialDialog.dismiss();
                    }
                });
        materialDialog.setCanceledOnTouchOutside(true);
        materialDialog.show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
